package com.zklink.restartzkserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableScheduling
public class RestartZkserverApplication {

    private final Logger logger = LoggerFactory.getLogger(RestartZkserverApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(RestartZkserverApplication.class, args);
    }

    private final RestTemplate restTemplate = new RestTemplate();

    @Value(value = "${zkserver}")
    private String zkServer;

    @Scheduled(fixedDelay = 180000)
    public void check() {
        Map<String, Object> data = new HashMap<>();
        data.put("jsonrpc", "2.0");
        data.put("id", 1);
        data.put("method", "account_info");
        data.put("params", Collections.singletonList("0xc7D9CD7cC37671526a4F1cD46280F7110db86D7e"));
        try {
            String response = restTemplate.postForObject(zkServer, data, String.class);
            logger.info(response);
        } catch (Exception e) {
            logger.error("Server error: {}", e.getMessage());
            restartServer();
        }
    }

    private void restartServer() {
        try {
            logger.info("Stop zkserver");
            Process process = Runtime.getRuntime().exec("supervisorctl stop zkserver");
            process.waitFor(3, TimeUnit.MINUTES);
            logger.info("Kill orphan children process");
            process = Runtime.getRuntime().exec("/root/kill-zkserver-orphan.sh");
            process.waitFor(3, TimeUnit.MINUTES);
            logger.info("Start zkserver");
            process = Runtime.getRuntime().exec("supervisorctl start zkserver");
            process.waitFor(3, TimeUnit.MINUTES);
            Thread.sleep(300000);
        } catch (IOException | InterruptedException e) {
            logger.error("Restart server error: {}", e.getMessage());
        }
    }
}
